package wei.xinya.concurrent;

import java.time.Duration;
import java.time.LocalTime;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;

public class Worker implements Runnable {
    private final CountDownLatch startSignal;
    private final CountDownLatch doneSignal;
    private final ConcurrentLinkedQueue<String> index;
    private final LocalTime localTime;

    Worker(CountDownLatch startSignal, CountDownLatch doneSignal, ConcurrentLinkedQueue<String> index, LocalTime localTime) {
        this.startSignal = startSignal;
        this.doneSignal = doneSignal;
        this.index = index;
        this.localTime = localTime;
    }

    public void run() {
        try {
            startSignal.await();
            doWork();
            doneSignal.countDown();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    void doWork() {
        String name = Thread.currentThread().getName();
        System.out.println(LocalTime.now() + " --- " + name + "开始干活");

        try {
            Random random = new Random();
            Thread.sleep(random.nextInt(10000));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        LocalTime now = LocalTime.now();
        Duration duration = Duration.between(localTime, now);

        index.add(name + " : 耗时 " + duration.toMillis() + "ms");
        System.out.println(now + " --- " + name + "活干好了");
    }

}
